<template>
  <main class="flex-1 p-8 bg-gray-100">
    <div class="bg-white rounded-lg shadow-md p-6">
      <!-- 搜索和操作区 -->
      <div class="mb-6 flex justify-between items-center">
        <div class="flex space-x-4">
          <el-input
                  v-model="searchKeyword"
                  placeholder="请输入权限名称"
                  class="w-64"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="statusFilter" placeholder="权限状态" class="w-32">
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </div>
        <div class="space-x-2">
          <el-button type="primary" icon="Plus" class="!rounded-button whitespace-nowrap" @click="showAddDialog">新增权限</el-button>
          <el-button type="danger" icon="Delete" class="!rounded-button whitespace-nowrap" @click="showBatchDeleteDialog">批量删除</el-button>
        </div>
      </div>

      <!-- 权限表格 -->
      <el-table
              :data="paginatedPermissions"
              @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="permissionName" label="权限名称" />
        <el-table-column prop="permissionType" label="权限类型" />
        <el-table-column prop="description" label="权限描述" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
                    v-model="scope.row.status"
                    :active-value="true"
                    :inactive-value="false"
                    @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" icon="Edit" size="small" class="!rounded-button whitespace-nowrap" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" icon="Delete" size="small" class="!rounded-button whitespace-nowrap" @click="showSingleDeleteDialog(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalItems"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑弹窗 -->
      <el-dialog title="编辑权限" v-model="isEditDialogVisible">
        <el-form :model="editForm">
          <el-form-item label="权限名称" label-width="100px">
            <el-input v-model="editForm.permissionName"></el-input>
          </el-form-item>
          <el-form-item label="权限类型" label-width="100px">
            <el-input v-model="editForm.permissionType"></el-input>
          </el-form-item>
          <el-form-item label="权限描述" label-width="100px">
            <el-input v-model="editForm.description" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isEditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleUpdatePermission">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 新增弹窗 -->
      <el-dialog title="新增权限" v-model="isAddDialogVisible">
        <el-form :model="addForm">
          <el-form-item label="权限名称" label-width="100px">
            <el-input v-model="addForm.permissionName"></el-input>
          </el-form-item>
          <el-form-item label="权限类型" label-width="100px">
            <el-input v-model="addForm.permissionType"></el-input>
          </el-form-item>
          <el-form-item label="权限描述" label-width="100px">
            <el-input v-model="addForm.description" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isAddDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleCreatePermission">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 单行删除弹窗 -->
      <el-dialog title="确认删除" v-model="isSingleDeleteDialogVisible">
        <p>确定要删除权限 <strong>{{ singleRowToDelete?.name }}</strong> 吗？</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isSingleDeleteDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSingleDelete">删除</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批量删除弹窗 -->
      <el-dialog title="确认批量删除" v-model="isBatchDeleteDialogVisible">
        <p>确定要删除所选权限吗？</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isBatchDeleteDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleBatchDelete">删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </main>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Search, Plus, Delete, Edit } from '@element-plus/icons-vue';
  import {getPermissionList,addPermission,updatePermission} from "../../api/admin/permission";
  const searchKeyword = ref('');
  const statusFilter = ref('');
  const currentPage = ref(1);
  const pageSize = ref(10);
  onMounted(async ()=>{
    getPermission()
  })
async function getPermission() {
  await getPermissionList(null).then(function (response) {
    permissionData.value=response.items[0]
  })
}
  const permissionData = ref([]);

  // 扁平化权限数据
  const flattenPermissions = (permissions) => {
    const result = [];
    const flatten = (items) => {
      items.forEach(item => {
        result.push(item);
        if (item.children && item.children.length > 0) {
          flatten(item.children);
        }
      });
    };
    flatten(permissionData.value);
    return result;
  };
  // 计算属性
  const filteredPermissions = computed(() => {
    const allPermissions = flattenPermissions(permissionData.value);
    return allPermissions.filter(permission =>
            permission.permissionName.includes(searchKeyword.value) &&
            (statusFilter.value === '' ||
                    (statusFilter.value === 'enabled' ? permission.status : !permission.status))
    );
  });
  const totalItems = computed(() => filteredPermissions.value.length);
  const paginatedPermissions = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredPermissions.value.slice(start, end);
  });


  const handleStatusChange = (row) => {
    ElMessage.success(`${row.permissionName}权限状态已${row.status ? '启用' : '禁用'}`);
  };

  const handleEdit = (row) => {
    editForm.value = { ...row };
    isEditDialogVisible.value = true;
  };

  const handleDelete = (row) => {
    ElMessage.warning(`删除权限：${row.name}`);
  };

  const handleSizeChange = (val) => {
    pageSize.value = val;
    // 这里应该重新加载数据
    getPermission()
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    // 这里应该重新加载数据
    getPermission()
  };

  const isEditDialogVisible = ref(false);
  const isAddDialogVisible = ref(false);
  const isSingleDeleteDialogVisible = ref(false);
  const isBatchDeleteDialogVisible = ref(false);

  const selectedRows = ref([]);

  const editForm = ref({});
  const addForm = ref({});
  const singleRowToDelete = ref(null);

  const showAddDialog = () => {
    isAddDialogVisible.value = true;
  };

  const handleUpdatePermission = () => {
    // 更新权限的逻辑
    console.log(editForm.value)
    updatePermission(editForm.value)
    isEditDialogVisible.value = false;
    ElMessage.success('权限已更新');
    getPermission()
  };

  const handleCreatePermission = () => {
    // 添加新权限的逻辑
    addPermission(addForm)
    isAddDialogVisible.value = false;
    ElMessage.success('权限已添加');
    getPermission()
  };

  const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
  };

  const showSingleDeleteDialog = (row) => {
    singleRowToDelete.value = row;
    isSingleDeleteDialogVisible.value = true;
  };

  const handleSingleDelete = () => {
    const index = permissionData.value.findIndex(item => item.id === singleRowToDelete.value.id);
    if (index !== -1) {
      permissionData.value.splice(index, 1);
      isSingleDeleteDialogVisible.value = false;
      ElMessage.success('权限已删除');
    }
  };

  const showBatchDeleteDialog = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择需要删除的权限');
      return;
    }
    isBatchDeleteDialogVisible.value = true;
  };

  const handleBatchDelete = () => {
    const idsToDelete = selectedRows.value.map(row => row.id);
    permissionData.value = permissionData.value.filter(item => !idsToDelete.includes(item.id));
    isBatchDeleteDialogVisible.value = false;
    ElMessage.success('权限已批量删除');
  };

  onMounted(() => {
    // 这里可以加载初始数据
  });
</script>

<style scoped>
  /* 自定义样式 */
  .el-table {
    --el-table-border-color: #e5e7eb;
    --el-table-header-background-color: #f3f4f6;
  }

  .el-pagination {
    --el-pagination-button-color: #1f2937;
    --el-pagination-hover-color: #3b82f6;
  }

  /* 确保按钮文字不换行 */
  .el-button {
    white-space: nowrap;
  }

  /* 移除 input type="number" 的默认箭头 */
  input[type="number"]::-webkit-inner-spin-button,
  input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  input[type="number"] {
    -moz-appearance: textfield;
  }
</style>

